const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * wx.request的异步封装
 */
function req(url, data = {}, method = "") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Accept': 'application/json',
        'ACCESS-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        resolve(res.data);
      },
      fail: function (res) {
        reject(res)
      }
    })
  });
}

// util.req(api.GetGoodInfomanage, {}, "").then(function (res) {
//   wx.showLoading({
//     title: '加载中',
//   })
//   if (res.success) {

//   }
// }).catch(function (res) {
//   console.log("获取数据失败！")
// })


/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'ACCESS-Token': wx.getStorageSync('token')
      },
      success: function (res) {

        if (res.statusCode == 200) {

          if (res.data.code == 501) {
            //TODO 此处还需要优化
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/auth/login/login'
            });
          } else if (res.data.code == 1) {
            resolve(res.data.obj);
          } else {
            // reject(res.errMsg);
            showErrorToast(res.data.msg);
          }
        } else {
          reject(res.data.msg);
        }

      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}


function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/images/icon_error.png'
  })
}

module.exports = {
  formatTime: formatTime,
  req,
  request,
  showErrorToast,
}

